package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//负责刷新token操作的拦截器
public class RefreshTokenInterceptor implements HandlerInterceptor {

    //拦截器 无法通过spring注解方式 注入 通过构造函数 添加拦截器的时候手动添加
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //负责刷新token操作的拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取token(前端authorization)
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            //4.不存在拦截
            return true;
        }
        //2. 根据token从redis中获取
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        //3. 判断用户是否存在
        if (userMap.isEmpty()){
           return true;
        }
        //5. 用户Hash转化回UserDao
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //6. 存在保存用户到ThreadLocal
        UserHolder.saveUser(userDTO);
        //7. 刷新有效时间
        stringRedisTemplate.expire(key   ,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //8. 放行
        return true;
    }


}
